package org.lboot.flow.module.event;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.flow.config.FlowControlConfig;
import org.lboot.jpa.jpa.AbstractJpaCurdExt;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class FlowCustomEventServiceImpl extends AbstractJpaCurdExt<String, FlowCustomEvent, FlowCustomEventDAO> implements FlowCustomEventService {
    FlowControlConfig config;
    @Override
    public List<FlowCustomEvent> getByEventId(String eventId) {
        List<FlowCustomEvent> events = dao.findByEventId(eventId);
        if (events.size() > 1){
            log.error("事件ID:[{}]存在重复数据项", eventId);
        }
        return events;
    }

    @Override
    public List<FlowCustomEvent> getByEventIdIn(List<String> eventIds) {
        return dao.findByEventIdIn(eventIds);
    }

    @Override
    public List<FlowCustomEvent> afterNodeEvents(String flowDefineId, String flowNodeId) {
        List<FlowCustomEvent> events = dao.findAll();
        List<FlowCustomEvent> matchEvents = events.stream().filter(event -> {
            // 绑定流程筛选
//            if (!event.getBindFlowId().equals("*") && !event.getBindFlowId().equals(flowDefineId)){
//                return false;
//            }
//            // 绑定节点筛选
//            if (!event.getBindNodeId().equals("*") && !event.getBindNodeId().equals(flowNodeId)){
//                return false;
//            }
            // 优先级筛选
            if (event.getPriority() >= config.systemEventPriority()){
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        return matchEvents;
    }

    @Override
    public List<FlowCustomEvent> beforeNodeEvent(String flowDefineId, String flowNodeId) {
        List<FlowCustomEvent> events = dao.findAll();
        List<FlowCustomEvent> matchEvents = events.stream().filter(event -> {
            log.info(event.toString());
            // 绑定流程筛选
//            if (!event.getBindFlowId().equals("*") && !event.getBindFlowId().equals(flowDefineId)){
//                return false;
//            }
//            // 绑定节点筛选
//            if (!event.getBindNodeId().equals("*") && !event.getBindNodeId().equals(flowNodeId)){
//                return false;
//            }
            // 优先级筛选
            if (event.getPriority() <= config.systemEventPriority()){
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        return matchEvents;
    }
}
